<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */
class CmsUrlManager extends CUrlManager
{
    public $RequestedPageUrl;
    
    private $_workflowLookupError = false;
    private $_noUrlCacheError = false;
        
    public function init(){
        if (isset($_GET['r']) && $this->urlFormat == 'path')
            $this->urlFormat = 'get';
                               
        $result = FSM::run('Cms.workflow.lookup');
        if ($this->getUrlFormat() == 'path')
        {
            if ($result->hasErrors() == false){
                $result = FSM::run('Cms.PageUrl.getCachedUrls',array('workflowUrl' => $result->model->url));
                if ($result->hasErrors() == false){
                    $urls = $result->urls;
                    //Add rules from page urls
                    foreach($urls as $url){
        //                $url = strtr($url,'[]','<>');
        //                $url = "<url:{$url}>";
                        if (is_array($url))
                        {
                            $this->rules[$url[1]] = $url[0];
                        }
                        elseif ($url != '/') //the root (homepage) rule will skip matching any rule after it
                            $this->rules[$url] = 'Cms/defaultCms/index';
                    }
                    //$this->rules['/'] = 'Cms/default/index';
                } else {
                    //we should throw an error but unfortunately, we cannot do that within UrlManager init()
                    //so we have to wait till parseUrl();
                    $this->_noUrlCacheError = true;
                }
            }else {
                //we should throw an error but unfortunately, we cannot do that within UrlManager init()
                //so we have to wait till parseUrl();
                $this->_workflowLookupError = true;
            }
        } else {
//            // make sure our Admin cannot be access from live
//            Yii::import('Cms.models.Workflow');
//            if (Yii::app()->cmsManager->workflow['type'] == Workflow::TYPE_FINAL && Yii::app()->request->getIsAjaxRequest() == FALSE)
//                if (! Yii::app()->session->contains('editMode') || Yii::app()->session['editMode'] == false)
//                    Yii::app()->request->redirect(baseUrl());
        }
        parent::init();
    }
    
    /**
     * Parses the user request.
     * This overrides original parseUrl() in case of PATH_FORMAT to get the rule that matches url if any
     * 
     * @param CHttpRequest the request application component
     * @return string the route (controllerID/actionID) and perhaps GET parameters in path format.
     */
    /**
     * Parses the user request.
     * @param CHttpRequest the request application component
     * @return string the route (controllerID/actionID) and perhaps GET parameters in path format.
     */
    public function parseUrl($request)
    {
        if($this->getUrlFormat()===self::PATH_FORMAT)
        {
            // check and throw some error we supposed to throw on the init but cannot because of Yii
            if ($this->_workflowLookupError === TRUE)
                throw new CHttpException(404,'Oups, looks like the domain is not configured properly to work with our CMS.');
            
            if ($this->_noUrlCacheError === TRUE)
                throw new Exception('Workflow for the requested URL is not defined yet.');
            // end of checking and throwing error
            
            $rawPathInfo=urldecode($request->getPathInfo());
            $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
            
            $pathInfo = Yii::app()->localeManager->processPathInfo($pathInfo);
            
            // can add code to modify url like mod_rewirte
            // ...
            // end of "mod_rewrite"
            foreach($this->rules as $pattern => $route)
            {
                $rule = new CUrlRule($route, $pattern);
                $rule->caseSensitive = false;
                if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false){
                    $this->RequestedPageUrl = $pattern;
                    return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
                }
            }
            if($this->useStrictParsing)
                throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
                    array('{route}'=>$pathInfo)));
            else
                return $pathInfo;
        }
        else if(isset($_GET[$this->routeVar]))
            $route = $_GET[$this->routeVar];
        else if(isset($_POST[$this->routeVar]))
            $route = $_POST[$this->routeVar];
        else
            $route = '';
        
        return $route;
    }
    
    public function createUrl($route,$params=array(),$ampersand='&')
    {
        if (!isset($params['layout']) && $this->getUrlFormat() === self::GET_FORMAT && Yii::app()->request->getParam('layout', '') === 'popup')
            $params['layout'] = 'popup';
        return parent::createUrl($route,$params,$ampersand);
    }
    
    /**
    * Create a friendly, absolute url for a model detail page
    * 
    * @param CActiveRecord $model
    * @param string $urlFormat
    */
    public function createModelUrl($model, $urlFormat){
        $urlFormat = trim($urlFormat);
        $matches = array();
        preg_match_all('/\[:[a-z0-9_]+\]/',$urlFormat,$matches);
        
        $r = array();
        $v = array();
        foreach($matches[0] as $param) {
            $property = substr(trim($param,'[]'),1);
            try {
                $value = $model->$property;
            }catch(Exception $ex){
                $value = '';
            }
            $r[] = $param;
            $v[] = $value;
        }
        
        return Yii::app()->request->getHostInfo().str_replace($r, $v, $urlFormat);
    }
}
?>